<?php

class Application_Model_LocataireMapper
{
	protected $_dbTable;
	
	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}
	
	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_Locataire');
		}
		return $this->_dbTable;
	}
	
	public function save(Application_Model_Locataire $loc)
	{
		$data = array(
				'nomcourtloc'   => $loc->getNomCourt(),
				'civiliteloc' => $loc->getCivilite(),
				'nomloc' => $loc->getNom(),
				'prenomloc' => $loc->getPrenom(),
				'telephoneloc' => $loc->getTelephone(),
				'portableloc' => $loc->getPortable(),
				'emailloc' => $loc->getEmail(),
				'adresseloc' => $loc->getAdresse(),
				'cploc' => $loc->getCp(),
				'villeloc' => $loc->getVille(),
				'noteloc' => $loc->getNote(),
		);
	
		if (null === ($id = $loc->getId())) {
			unset($data['idlocataire']);
			$this->getDbTable()->insert($data);
		} else {
			$this->getDbTable()->update($data, array('idlocataire = ?' => $id));
		}
	}
	
	public function find($id, Application_Model_Locataire $loc)
	{
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) {
			return;
		}
		$row = $result->current();
		$loc->setId($row->idlocataire)
			->setNomCourt($row->nomcourtloc)
			->setCivilite($row->civiliteloc)
			->setNom($row->nomloc)
			->setPrenom($row->prenomloc)
			->setTelephone($row->telephoneloc)
			->setPortable($row->portableloc)
			->setEmail($row->emailloc)
			->setAdresse($row->adresseloc)
			->setCp($row->cploc)
			->setVille($row->villeloc)
			->setNote($row->noteloc);
	}
	
	public function fetchAll()
	{
		$resultSet = $this->getDbTable()->fetchAll();
		$entries   = array();
		foreach ($resultSet as $row) {
			$entry = new Application_Model_Locataire();
			$entry->setId($row->idlocataire)
				->setNomCourt($row->nomcourtloc)
				->setCivilite($row->civiliteloc)
				->setNom($row->nomloc)
				->setPrenom($row->prenomloc)
				->setTelephone($row->telephoneloc)
				->setPortable($row->portableloc)
				->setEmail($row->emailloc)
				->setAdresse($row->adresseloc)
				->setCp($row->cploc)
				->setVille($row->villeloc)
				->setNote($row->noteloc);
			$entries[] = $entry;
		}
		return $entries;
	}

}

